package com.ihg.hiex.admin.web.interceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 *
 * @author Ark
 *
 */
public class IhgLocaleChangeInterceptor extends LocaleChangeInterceptor {
    
    private static final String IHG_LOCALE = "ihg_locale";

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.i18n.LocaleChangeInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws ServletException {
        
        // 1. Get user choose language from session
        HttpSession httpSession = request.getSession();
        String ihgLocale = (String) httpSession.getAttribute(IHG_LOCALE);
        
        // 2. Get current system i18n language
        String newLocale = request.getParameter(getParamName());
        if (StringUtils.isNotBlank(newLocale)) {
            httpSession.setAttribute(IHG_LOCALE, newLocale);
        } else {
            newLocale = ihgLocale;
        }
        
        // 3. construct localeResolver
        if (newLocale != null) {
            if (checkHttpMethod(request.getMethod())) {
                LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
                if (localeResolver == null) {
                    throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
                }
                
                try {
                    localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
                } catch (IllegalArgumentException ex) {
                    if (isIgnoreInvalidLocale()) {
                        logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + ex.getMessage());
                    } else {
                        throw ex;
                    }
                }
            }
        }
        
        // Proceed in any case.
        return true;
        
    }
    
    /**
     * @param currentMethod
     * @return
     */
    private boolean checkHttpMethod(String currentMethod) {
        String[] configuredMethods = getHttpMethods();
        if (ObjectUtils.isEmpty(configuredMethods)) {
            return true;
        }
        for (String configuredMethod : configuredMethods) {
            if (configuredMethod.equalsIgnoreCase(currentMethod)) {
                return true;
            }
        }
        return false;
    }
    
}
